import { RegClass } from "../core/serialize";
import AppNode from "../core/app_node.ts";
import { EleDiv, EleInput, EleSpan } from "../core/data_ext.ts";
import { ProtocolC2SLoginUser, ProtocolC2SLogoutUser, ProtocolC2SRegUser, ProtocolObjectUser, ProtocolS2CLoginUser, ProtocolS2CRegUser } from "../protocol_dist.ts";
import SocketCtrl from "./socket_ctrl.ts";
import { Sync } from "../core/utils.ts";

@RegClass("UserItem")
export default class UserItem extends AppNode {
    lbName: EleDiv = null;
    lbUUid: EleDiv = null;
    lbLogin: EleSpan = null;
    lbLoginTime: EleSpan = null;

    user: ProtocolObjectUser = null;
    token = "";
    async onLoad() {
        await Sync.DelayTime(0.1);
        SocketCtrl.ins.addListener(ProtocolS2CRegUser, this.onRegUser, this);
        SocketCtrl.ins.addListener(ProtocolS2CLoginUser, this.onLoginUser, this);
    }
    onDispose(): void {
        SocketCtrl.ins.targetOff(this);
    }
    onMessage(msg: ProtocolS2CRegUser) {
        if (msg.ok) {
            this.setData(this.user);
        }
    }
    onRegUser(msg: ProtocolS2CRegUser) {
        if (msg.ok) {
            this.setData(msg.user);
        }
    }
    onLoginUser(msg: ProtocolS2CLoginUser) {
        if (msg.ok) {
            this.setData(msg.user);
        }
    }
    setData(user: ProtocolObjectUser) {
        this.user = user;
        if (this.user) {
            this.lbLogin.innerText = "已登录";
            this.lbLoginTime.innerText = (new Date(this.user.sessionTime*1000)).toTimeString();
            this.lbUUid.innerText = this.user.token;
            this.lbName.innerText = "无名";
            this.token = this.user.token;
        }
        else {
            this.lbLogin.innerText = "未登录";
            this.lbLoginTime.innerText = "";
            this.lbUUid.innerText = "";
            this.lbName.innerText = "";
        }
    }

    onClickReg() {
        if (this.user) {
            return;
        }
        let msg = new ProtocolC2SRegUser();
        SocketCtrl.ins.sendMessage(msg);
    }
    onClickLogin() {
        if (this.user) {
            return;
        }
        let msg = new ProtocolC2SLoginUser();
        msg.token = this.token;
        SocketCtrl.ins.sendMessage(msg);
    }
    onClickLogout() {
        let msg = new ProtocolC2SLogoutUser();
        SocketCtrl.ins.sendMessage(msg);
        this.setData(null);
    }

};